package com.nai365.nart.seckill.controller;

import cn.hutool.core.lang.Console;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.common.security.annotation.Inner;
import com.nai365.nart.common.security.util.SecurityUtils;
import com.nai365.nart.seckill.constant.SeckillConstant;
import com.nai365.nart.seckill.dto.SeckillInputTo;
import com.nai365.nart.seckill.dto.SeckillSkuRedisTO;
import com.nai365.nart.seckill.service.SeckillService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description:
 * @Created: with IntelliJ IDEA.
 * @author: baogs
 * @createTime: 2022-07-10 11:01
 **/
@RestController
@RequiredArgsConstructor
@RequestMapping("/seckill")
@Api(value = "seckill", tags = "抢购管理")
public class SeckillController {


    @Autowired
    private SeckillService seckillService;

    /**
     * 查询当前时间可以参与秒杀的商品列表
     */
    // @SentinelResource(value = "getCurrentSeckillSkus") 配置sentinel资源，默认情况下所有请求都是资源，无需配置
    @GetMapping(value = "/getCurrentSeckillSkus")
    @ResponseBody
    public R getCurrentSeckillSkus() {
        List<SeckillSkuRedisTO> results = seckillService.getCurrentSeckillSkus();
        return R.ok(results);
    }

//    /**
//     * 根据skuId查询商品当前时间秒杀信息
//     */
//    @GetMapping(value = "/sku/seckill/{skuId}")
//    @ResponseBody
//    public R getSkuSeckilInfo(@PathVariable("skuId") Long skuId) {
//        SeckillSkuRedisTO to = seckillService.getSkuSeckilInfo(skuId);
//        return R.ok(to);
//    }


	    /**
     * 根据skuId查询商品当前时间秒杀信息
     */
    @GetMapping(value = "/close_order_stock_handler")
    @ResponseBody
	@Inner
    public R getSkuSeckilInfo(@RequestParam("skuId") Long skuId) {
        return seckillService.closeOrderHandler(skuId);
    }

    /**
     * 秒杀商品
     * 1.校验登录状态
     * 2.校验秒杀时间
     * 3.校验随机码、场次、商品对应关系
     * 4.校验信号量扣减，校验购物数量是否限购
     * 5.校验是否重复秒杀（幂等性）【秒杀成功SETNX占位  userId_sessionId_skuId】
     * 6.扣减信号量
     * 7.发送消息，创建订单号和订单信息
     * 8.订单模块消费消息，生成订单
     * @param killId    sessionId_skuid
     * @param key   随机码
     * @param num   商品件数
     * @param model
     * @return
     */
    @PostMapping(value = "/kill")
    public R seckill(@RequestBody SeckillInputTo seckillInputTo) {
        R orderSn = null;
        try {
            orderSn = seckillService.kill(seckillInputTo.getSpuId(),"",0,seckillInputTo.getOrderType(),seckillInputTo.getDataId(), SecurityUtils.getUser().getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return orderSn;
    }


	@GetMapping(value = "/kill_inner")
	@Inner
	public R seckillInner(@RequestParam("spuId") String spuId, @RequestParam("orderType") Integer orderType,@RequestParam("dataId") Long dataId,@RequestParam("userId") Long userId) {
		R orderSn = null;
		try {
			orderSn = seckillService.kill(spuId,"",0,orderType,dataId,userId);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return orderSn;
	}
    @GetMapping(value = "/sku_count")
	@Inner
    public R seckillCount(@RequestParam("spuId") String spuId) {

        return R.ok(seckillService.getCurrentSkuCountBysSpu(spuId));
    }
    @GetMapping(value = "/save_session")
	@Inner
    public R saveSession(String spuId) {
		seckillService.uploadSeckillSkuById(spuId);
        return R.ok();
    }
    @GetMapping(value = "/delete_session")
	@Inner
    public R deleteSession(String spuId) {
		seckillService.downSeckillSkuById(spuId);
        return R.ok();
    }


}
